package com.xspace.android.xafcommon.db.dbsub;

import android.content.ContentValues;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;

import com.xspace.android.xafcommon.been.AppListInfoBean;
import com.xspace.android.xafcommon.db.BaseSql;
import com.xspace.android.xafcommon.util.LogUtil;

import java.util.ArrayList;
import java.util.List;



public class AppDownDBBiz extends BaseSql {

	private String appInfoTable = "appinfo";

	private String app_id = "app_id";
	private String appName = "name";
	private String package_name = "package_name";
	private String load_integral = "load_integral";

	public AppDownDBBiz(MyDBHelper db) {
		super(db);
	}

	public AppDownDBBiz() {

	}

	@Override
	public void create(SQLiteDatabase db) {
		db.execSQL("CREATE TABLE " + appInfoTable + " (_ID INTEGER PRIMARY KEY AUTOINCREMENT," + app_id + " text," + appName + " text," + package_name + " text," + load_integral
				+ " text);");

	}

	public void dropTable(SQLiteDatabase db) {
		db.execSQL(TB_DELETE + appInfoTable);
	}

	@Override
	public void upgrade(SQLiteDatabase db) {
	}

	/**
	 * 保存sort数据到本地数据库
	 */
	public int saveSort(AppListInfoBean mBean) {
		where = app_id + "='" + mBean.id + "' and " + appName + "='" + mBean.name + "' and " + load_integral + "='" + mBean.load_integral + "' and " + package_name + "='"
				+ mBean.package_name + "'";
		values = new ContentValues();

		values.put(app_id, mBean.id);
		values.put(appName, mBean.name);
		values.put(package_name, mBean.package_name);
		values.put(load_integral, mBean.load_integral);
		LogUtil.d("AppDownDBBiz==>" + where);
		return super.saveOrUpdate(appInfoTable);

	}

	/**
	 * 查询保存的app信息
	 */
	public List<AppListInfoBean> queryDownAppInfo() {
		List<AppListInfoBean> list = new ArrayList<AppListInfoBean>();

		try {
			Cursor cur = db.query(appInfoTable, null);

			if (cur != null) {
				for (int i = 0; i < cur.getCount(); i++) {
					if (cur.moveToPosition(i)) {
						AppListInfoBean bean = new AppListInfoBean();
						bean.id = cur.getString(1);
						bean.name = cur.getString(2);
						bean.package_name = cur.getString(3);
						bean.load_integral = cur.getString(4);
						list.add(bean);
					}
				}
				cur.close();
			}
		} catch (Exception e) {
			e.printStackTrace();

		} finally {
			db.close();
		}

		return list;
	}

	/**
	 * 删除保存的sort信息
	 */
	public int deletAppInfo(String mPackage_name) {
		selection = package_name + "='" + mPackage_name + "'";
		return super.delete(appInfoTable);
	}

}
